package com.wss.common.base;

import com.wss.common.base.mvp.BasePresenter;
import com.wss.common.base.mvp.IBaseView;
import com.wss.common.widget.dialog.LoadingDialog;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleObserver;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.app.Context;

public abstract class BaseMvpFragment<P extends BasePresenter> extends BaseFragment implements IBaseView {

    private P presenter;
    private LoadingDialog loadingDialog;
    protected boolean isInit = false;

    public BaseMvpFragment(Ability ability) {
        super(ability);
    }

    @Override
    public void onViewCreated(Component view) {
        super.onViewCreated(view);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        init();
    }

    public void init() {
        if (!isInit) {
            isInit = true;
            loadingDialog = new LoadingDialog(context);
            loadingDialog.setCancelable(loadingCancelable());
            //创建present
            presenter = createPresenter();
            if (presenter != null) {
                presenter.attachView(this);
            }
            initView();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (presenter != null) {
            presenter.detachView();
        }
    }

    @Override
    public Context getContext() {
        return ability.getContext();
    }

    /**
     * 返回presenter
     *
     * @return P
     */
    public P getPresenter() {
        return presenter;
    }

    public Component findComponentById(int resId) {
        return getRootView().findComponentById(resId);
    }

    //***************************************IBaseView方法实现 start *************************************

    @Override
    public void showLoading() {
        if (loadingDialog != null && !loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        hideEmptyView();
    }

    @Override
    public void dismissLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 加载框是否可以取消
     *
     * @return boolean
     */
    protected boolean loadingCancelable() {
        return true;
    }

    @Override
    public void onEmpty(Object tag) {
        dismissLoading();
    }

    @Override
    public void onError(Object tag, String errorMsg) {
        dismissLoading();
    }

    @Override
    public Lifecycle getLifecycleOwner() {
        return ability.getLifecycle();
    }

    //***************************************IBaseView方法实现 end*************************************

    /**
     * 创建Presenter
     *
     * @return Presenter
     */
    protected abstract P createPresenter();
}
